<template>
	<view class="chat">
			<common-view :indicator="indicator" :animation="animation" @closeAnimation="closeAnimation"></common-view>
			<view class="cu-chat" :style="'height:'+(winHeight-barHeight-footHeight)+'px;display:flex;position: relative;width:100%;'">
				<scroll-view :scroll-into-view="scrollIntoViewId" class="page bg-ededed" :scroll-y="true" :style="'height:'+(winHeight-barHeight-footHeight)+'px;'">
					<view v-if="msgCount>30"  class="cu-info">
						查看更多聊天记录
					</view>
					<view style="height:30upx;"></view>
					<block v-for="(item,index) in myMsgList" :key="index">
						<view v-if="item.id==userInfo.user_id" class="cu-item self">
							<view v-if="item.timestampStr" class="date">{{item.timestampStr}}</view>
							<view class="flex justify-end" style="width:100%">
								<view class="main" :style="item.type=='json'?'flex-grow:1;':''">
									<block v-if="item.type!='img'">
										<block v-if="item.send==1 && reSendStatus!=index">
											<view class="action" @click="reSend" :data-key="index">
												<text class="icon-infofill text-red text-xxl"></text>
											</view>
										</block>
										<block v-if="reSendStatus==index">
											<view class="action">
												<text class="icon-loading2 text-gray text-xxl"></text>
											</view>
										</block>
										
									</block>
									<block v-if="item.type=='img'">
										<view class="imgBox">
											<block v-if="item.send==1 && reSendStatus!=index">
												<view class="action" @click="reSend" :data-key="index">
													<text class="icon-infofill text-red text-xxl"></text>
												</view>
											</block>
											<block v-if="item.send==0 && reSendStatus!=index">
												<view class="action" @click="reSend" :data-key="index">
													<text class="icon-loading2 text-gray text-xxl"></text>
												</view>
											</block>
											<block v-if="reSendStatus==index">
												<view class="action">
													<text class="icon-loading2 text-gray text-xxl"></text>
												</view>
											</block>
											<image @click="previewPic" :data-src="item.content" :src="item.content" class="radius" mode="widthFix" style="background:#fff;"></image>
										</view>
									</block>
									<block v-if="item.type=='json'">
										<view class="content bg-themeColor text-baseColor shadow">
											<rich-text :nodes="'<div>'+item.content.content+'</div>'"></rich-text>
										</view>
									</block>
									<block v-if="item.type=='text'">
										<view class="content bg-themeColor text-baseColor shadow">
											<rich-text :nodes="'<div>'+item.content+'</div>'"></rich-text>
										</view>
									</block>
								</view>
								<navigator hover-class="none" :url="'../../pages/friend/profile?mid='+item.id">
									<view class="cu-avatar radius">
										<image :src="item.avatar+'_100'" class="radius" mode="aspectFill"></image>
									</view>
								</navigator>
							</view>
							
						</view>
						<view v-else class="cu-item">
							<view v-if="item.timestampStr" class="date">{{item.timestampStr}}</view>
							<view class="flex" style="width:100%">
								<!-- <navigator v-if="item.type!='json'" hover-class="none" :url="'../../pages/friend/profile?mid='+item.id"> -->
								<navigator hover-class="none" :url="'../../pages1/contacts/profile?uid='+item.from_id">
									<view class="cu-avatar radius">
										<image v-if="item.type=='friend'" :src="item.avatar+'_100'" class="radius" mode="aspectFill"></image>
										<image v-else :src="item.from_avatar+'_100'" class="radius" mode="aspectFill"></image>
									</view>
								</navigator>
								<view class="flex flex-direction" style="width:100%">
									<view v-if="msgType=='group'" class="text-xs text-gray" style="margin-left:34upx;">{{item.from_name}}</view>
									<!-- <view class="main" style="flex-grow:1;" :class="item.type=='json'?'json-msg':''"> -->
									<view class="main" style="flex-grow:1;">
										<block v-if="item.type=='img'">
											<image @click="previewPic" :data-src="item.content" :src="item.content" class="radius" mode="widthFix" style="background:#fff;"></image>
										</block>
										<block v-if="item.type=='text'">
											<view class="content shadow">
												<rich-text :nodes="'<div>'+item.content+'</div>'"></rich-text>
											</view>
										</block>
										<block v-if="item.type=='json'">
											<view class="content shadow" style="padding:0; flex-grow:1;">
												<view class="cu-list menu card-menu" style="margin:0;width:100%;">
													<view class="cu-item" style="min-height:80upx;flex-direction:row;">
														<view style="font-weight: bold;">
															{{item.content.title}}
														</view>
													</view>
													<view class="cu-item" style="padding: 0;">
														<view class="order_menu text-df" style="padding:20upx;">
															<rich-text :nodes="'<div>'+item.content.content+'</div>'"></rich-text>
														</view>
													</view>
													<view v-if="item.content.navigator" :data-navigator="item.content.navigator" :data-navigator-url="item.content.navigatorUrl" @click="toMsgDetail" class="cu-item arrow" style="min-height:80upx;flex-direction:row;">
														<view style="color: #378EED;font-size: 25upx;line-height: 25upx;">
															查看详情
														</view>
													</view>
												</view>
											</view>
										</block>
										
									</view>
								</view>
							</view>
							
						</view>
					</block>
					<view id="msg-bottom-view-1" style="width:100%;height:2upx;"></view>
					<view id="msg-bottom-view-2" style="width:100%;height:2upx;"></view>
				</scroll-view>
			</view>

			<view class="foot bg-white" :style="'height:'+footHeight+'px;'">
				<view class="cu-bar input">
					<view class="action" @click="toSendVoice">
						<text class="icon-sound text-grey"></text>
					</view>
					
					<!-- #ifdef MP-WEIXIN || H5 -->
					<input class="solid-bottom" :adjust-position="true" :focus="false" maxlength="300" cursor-spacing="20" @focus="inFocus" @input="inputValue" :value="msgContent"></input>
					<!-- #endif -->
					
					<!-- #ifndef MP-WEIXIN || H5 -->
					<view  class="solid-bottom" :style="'width:'+inputW+'px'" style="padding: 0 10upx;">
						<textarea style="min-height:32upx;line-height:45upx;margin:10upx 0;max-height: 500upx;width:100%;" :fixed="true" auto-height maxlength="300" cursor-spacing="10" :show-confirm-bar="false" @input="inputValue" :value="msgContent" @focus="inFocus"/>
					</view>
					<!-- #endif -->
					
					<view class="action" @click="openFacePlace">
						<text class="icon-emojifill text-grey"></text>
					</view>
					<view v-if="msgContent==''" class="action" @click="choicePic">
						<text class="icon-pic text-grey"></text>
					</view>
					<view v-if="msgContent!=''" class="action">
						<button class="cu-btn bg-themeColor shadow" @click="sendMsg">
							<view>发送</view>
						</button>
					</view>
					
				</view>
			</view>

		
		<view class="cu-modal bottom-modal" :class="modalShow?'show':''" @tap="hideModal">
			<view class="cu-dialog" style="z-index:9999;" :style="'bottom:'+footHeight+'px;'" @tap.stop="" >
				<scroll-view class="scrollPage" scroll-y="true" :style="'height:'+(faceListHeight)+'px'">
					<view class="face-list">
						<view class="face" v-for="(item,index) in faceList" :key="index" @click="choiceFace" :data-alt="item">{{item}}</view>
					</view>
				</scroll-view>
				
			</view>
			
		</view>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex';
	import util from 'common/util.js';
	import chat from 'model/chatModel.js'
	import uploadFileObj from 'model/uploadFileModel.js'
	const env = require('../../components/ali-oos/config.js')
	let disp = require("common/broadcast");
	let me = null;
	export default {
		data() {
			return {
				indicator:0,
				scrollTop:0,
				customShow:0,
				safeAreaHeight:this.SafeAreaHeight,
				height: 0,
				footHeight:0,
				faceListHeight:0,
				title:'',
				myMsgList:{},
				friendId:0,
				msgType: 'friend',
				msgContent:'',
				unRead:0,
				modalShow:0,
				faceList:util.faces,
				tempTime:0,
				reSendStatus:-1,
				picList:[],
				msgCount:0,
				animation: '',
				inputW:0,
				isReady:0,
				barHeight: 0,
				scrollIntoViewId:''
			};
		},
		onLoad(option) {
			me = this;
			this.friendId = option.friendid;
			this.unRead = option.unread;
			this.msgType = option.msgType;
			this.barHeight = this.CustomBar;
		
			this.faceListHeight = uni.upx2px(560)+this.SafeAreaHeight/2;
			this.footHeight = uni.upx2px(100)+this.SafeAreaHeight/2;
			this.inputW = uni.getSystemInfoSync().windowWidth - uni.upx2px(300);
			uni.onWindowResize((res) => {
				this.onWindowResizeEvent();
			});
			if(uni.getSystemInfoSync().platform=='ios'){
				// #ifdef APP-PLUS
				// this.$mp.page.$getAppWebview().setStyle({
				//   softinputNavBar: 'none'
				// });
				this.$scope.$getAppWebview().setStyle({
				  softinputNavBar: 'none'
				})
				// #endif
				
			}
			this.title = this.chatTo['name'];
			
	
			//this.myMsgList = this.transferData(this.historyMsgList);
		},
		onShow() {
			this['chatModule/setChatWindowsId'](this.friendId);
			console.log("friendId:"+this.friendId);
			
		},
		onReady() {
			me.isReady = 1;
			uni.setNavigationBarTitle({title:this.title});
			this.height = this.WindowHeight - this.CustomBar - 1 -this.footHeight;
			// #ifdef APP-PLUS
			this.height = uni.getSystemInfoSync().windowHeight-this.footHeight+this.StatusBar;
			// #endif
			this.setRead();
			
			
			// console.log(this.faceList)
			
		},
		onHide() {
			console.log('chat page onHide');
			//this['chatModule/setChatWindowsId'](0);
			//this['chatModule/setChatTo']({});
			uni.offWindowResize(() => {
				console.log('取消监听窗口尺寸变化事件')
			});
		},
		onUnload() {
			console.log('chat page onUnload');
			this['chatModule/setChatWindowsId'](0);
			this['chatModule/setChatTo']({});
			uni.offWindowResize(() => {
				console.log('取消监听窗口尺寸变化事件')
			});
		},
		computed: {
			...mapState({
				winHeight: ({baseModule}) => baseModule.winHeight,
				navHeight: ({baseModule}) => baseModule.navHeight,
				hasLogin:({userModule})=>userModule.hasLogin,
				userInfo:({userModule})=>userModule.userInfo,
				historyMsgList: ({chatModule}) => chatModule.historyMsgList,
				unreadMsgCount: ({chatModule}) => chatModule.unreadMsgCount,
				chatTo: ({chatModule}) => chatModule.chatTo
			})
		},
		watch: {
			historyMsgList(val) {
				me.myMsgList = me.transferData(val);
				this.$nextTick(function() {
				 	this.scrollToBottom(0);
				});
			},
			footHeight(val){
				me.scrollToBottom(0);
			}
		},
		methods: {
			...mapMutations(['chatModule/setChatWindowsId', 'chatModule/setHistoryMsgList', 'chatModule/setUnreadMsgCount', 'chatModule/setChatTo']),
			inputValue(e){
				this.msgContent = e.target.value;
				this.updateFootHeight();
				me.scrollToBottom();
			},
			transferData(msgList){
				var myChatLog = [];
				var nextTime = 0;
				myChatLog = util.deepCopy(msgList[me.userInfo.user_id][me.msgType+me.friendId]['chatlog']||[]);
				for(var i=0;i<myChatLog.length;i++){
					if(i>0){
						nextTime = myChatLog[i-1]['timestamp'];
					}
					if((myChatLog[i]['timestamp']-nextTime)>5*60*1000){
						myChatLog[i]['timestampStr'] = util.transferDate2(myChatLog[i]['timestamp']);
					}
					else{
						myChatLog[i]['timestampStr'] = "";
					}
					if(/img\[([^\s]+?)\]/.test(myChatLog[i]['content'])) {
						myChatLog[i]['type'] = 'img';
						myChatLog[i]['content'] = myChatLog[i]['content'].replace(/(^img\[)|(\]$)/g, '');
					}
					else if(/json\[.*\]/.test(myChatLog[i]['content'])) {
						myChatLog[i]['type'] = 'json';
						var str = myChatLog[i]['content'].replace(/(^json\[)|(\]$)/g, '');
						str = str.replace(/&amp;/g, '&');
						str = str.replace(/&lt;/g, '<');
						str = str.replace(/&gt;/g, '>');
						str = str.replace(/&quot;/g, '"');
						str = str.replace(/&#039;/g, "'");
						str = str.replace(/&#39;/g, "'");
						var obj = JSON.parse(str);
						//console.log(obj);
						myChatLog[i]['content'] = obj;
					}
					else{
						myChatLog[i]['type'] = 'text';
						myChatLog[i]['content'] = util.transferContent3(myChatLog[i]['content']);
					}
					
				}
				//console.log(myChatLog);
				me.msgCount = myChatLog.length;
				
				return myChatLog;
			},
			previewPic(event){
				console.log([event.currentTarget.dataset['src']])
				uni.previewImage({
					current:0,
					urls: [event.currentTarget.dataset['src']]
				});
			},
			setRead(){
				var num;
				var historyMsgListCopy = util.deepCopy(this.historyMsgList);
				if(!historyMsgListCopy[me.userInfo.user_id]){
					return false;
				}
				if(!historyMsgListCopy[me.userInfo.user_id][me.msgType+me.friendId]){
					return false;
				}
				if(!historyMsgListCopy[me.userInfo.user_id][me.msgType+me.friendId]['chatlog']){
					return false;
				}
				var myChatLog = historyMsgListCopy[me.userInfo.user_id][me.msgType+me.friendId]['chatlog']||[];
				for(var i=0;i<myChatLog.length;i++){
					if(myChatLog[i]['read']==0){
						myChatLog[i]['read'] = 1;
						num++;
					}
				}
				me['chatModule/setUnreadMsgCount'](me.unreadMsgCount - num);
				me['chatModule/setHistoryMsgList'](historyMsgListCopy);
				me.setStore('historyMsgList', historyMsgListCopy);
			},
			sendMsg(){
				var msg = {};
				msg.key = util.uuid();
				msg.type =me.msgType;
				msg.id = me.userInfo.user_id;
				msg.name = me.userInfo.username;
				msg.content = this.msgContent;
				msg.avatar = me.userInfo.avatar;
				msg.from_id = me.userInfo.user_id;
				msg.from_avatar = me.userInfo.avatar;
				msg.from_name = me.userInfo.username;
				msg.timestamp = new Date().getTime();
				msg.mine = true;
				msg.to=me.chatTo;
				msg.send = 0;
				chat.saveMsg(me,msg,"send");
				me.doSend(msg,0);
				this.msgContent="";
				me.scrollToBottom(0);
			},
			doSend(msg,reSend){
				// console.log(msg);
				var sendData={
					'data[mine][name]': msg.name,
					'data[mine][avatar]': msg.avatar,
					'data[mine][id]': msg.id,
					'data[mine][mine]': true,
					'data[content]': msg.content,
					'data[key]': msg.key,
					'data[to][id]': msg.to['id'],
					'data[to][name]': msg.to['name'],
					'data[to][avatar]': msg.to['avatar'],
					'data[type]': msg.to['type']
				};
				// console.log(sendData);
		
				chat.sendMsg(me,sendData,function(){
					console.log('发送成功')
					if(reSend){me.reSendStatus=-1;}
					chat.sendStatus(me,msg,true);
				},function(){
					console.log('发送失败')
					if(reSend){me.reSendStatus=-1;}
					chat.sendStatus(me,msg,false);
				});
			},
			hideModal(e) {
				this.modalShow = 0;
			},
			openFacePlace(){
				this.modalShow = 1;
			},
			choiceFace(e){
				me.msgContent=me.msgContent+e.target.dataset['alt'];
				this.modalShow = 0;
			},
			toSendVoice(){
				uni.showToast({
					title: '暂不支持语音消息',
					icon: 'none',
					duration: 1000
				});
			},
			choicePic(){
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function (res) {
						for(var key in res.tempFilePaths){
							// #ifdef H5
							me.sendPic(res.tempFilePaths[key]);
							// #endif
							
							// #ifndef H5
							uni.saveFile({
							  tempFilePath: res.tempFilePaths[key],
							  success: function (res2) {
								me.sendPic(res2.savedFilePath);
							  }
							});
							// #endif
							
							
						}
					}
				});
			},
			sendPic(path){
				var msg = {};
				msg.key = util.uuid();
				msg.type =me.msgType;
				msg.id = me.userInfo.user_id;
				msg.name = me.userInfo.username;
				msg.content = "img["+path+"]";
				msg.avatar = me.userInfo.avatar;
				msg.timestamp = new Date().getTime();
				msg.from_id = me.userInfo.user_id;
				msg.from_avatar = me.userInfo.avatar;
				msg.from_name = me.userInfo.username;
				msg.mine = true;
				msg.to=me.chatTo;
				msg.send = 0;
				// console.log(msg);
				chat.saveMsg(me,msg,"send");
				me.uploadPic(msg,path,0);
				// me.doSend(msg,0);
				// this.msgContent="";
				me.scrollToBottom(0);
			},
			uploadPic(msg,path,reSend){
				// console.log(path);
				var msgCopy = util.deepCopy(msg);
				var fileKey = env.uploadImageUrl + 'im/' + new Date().getTime() + Math.floor(Math.random() * 150) + util.getSuffix(path);
				// console.log(fileKey);
				uploadFileObj.uploadFile(fileKey, path).then(res => {
					msgCopy.content = "img["+env.fileHost+"/"+fileKey+"]";
					chat.edtMsg(me,msgCopy);
					me.doSend(msgCopy,reSend);
				}).catch(err => {
					chat.sendStatus(me,msg,false);
				});
			},
			onWindowResizeEvent(){
				me.scrollToBottom(0);
			},
			closeAnimation() {
				this.animation = "";
				this.indicator = 0;
			},
			scrollToBottom(dur){
				this.$nextTick(() => {
					this.scrollIntoViewId='msg-bottom-view-1';
					this.$nextTick(() => {
						this.scrollIntoViewId='msg-bottom-view-2';
						this.$nextTick(() => {
							this.scrollIntoViewId='';
						});
					});
				});
				
				// this.scrollIntoViewId='';
				// if(me.isReady==0){
				// 	return false;
				// }
				// let cuChat = uni.createSelectorQuery().select(".cu-chat");
				// cuChat.fields({
				// 	size: true
				// }, data => {
				// 	// console.log(data.height);
				// 	uni.pageScrollTo({
				// 		scrollTop: data.height,
				// 		duration: dur
				// 	});
				// }).exec();
			},
			updateFootHeight(){
				// let cuChat = uni.createSelectorQuery().select(".foot");
				// cuChat.fields({
				// 	size: true
				// }, data => {
				// 	// console.log(data.height);
				// 	me.footHeight = data.height;
				// }).exec();
			},
			inFocus(e){
				me.scrollToBottom(0);
			},
			reSend(e){
				if(me.reSendStatus!=-1){
					return false;
				}
				me.reSendStatus=e.currentTarget.dataset['key'];
				var msg = me.historyMsgList[me.userInfo.user_id][me.msgType+me.friendId]['chatlog'][me.reSendStatus];
				console.log(msg);
				if(/img\[([^\s]+?)\]/.test(msg['content'])) {
					//msg['content'].replace(/(^img\[)|(\]$)/g, '')
					me.uploadPic(msg,msg['content'].replace(/(^img\[)|(\]$)/g, ''),1);
				}
				else{
					me.doSend(msg,1);
				}
			},
			getDataTime(timestamp,key){
				console.log(key)
				if(key==0){
					return util.transferDate2(timestamp);
				}
				else{
					var myChatLog = [];
					myChatLog = util.deepCopy(me.historyMsgList[me.userInfo.user_id][me.msgType+me.friendId]['chatlog']||[]);
					var nextTime = myChatLog[key-1]['timestamp'];
					if((timestamp-nextTime)>300*1000){
						me.tempTime = timestamp;
						return util.transferDate2(timestamp);
					}
					else{
						return "";
					}
				}
			},
			toMsgDetail(e){
				if(e.currentTarget.dataset['navigator']=="page"){
					uni.navigateTo({
						url:e.currentTarget.dataset['navigatorUrl']
					})
				}
				if(e.currentTarget.dataset['navigator']=="tab"){
					disp.fire("changePageCur", e.currentTarget.dataset['navigatorUrl']);
					uni.navigateBack({
						delta:1
					})
				}
			}
		}
	}
</script>

<style>
.radius {
    border-radius: 6upx;
}
/* .cu-bar{
	height: calc(100upx + env(safe-area-inset-bottom) / 1.5);
	padding-bottom: calc(env(safe-area-inset-bottom) / 1.5);
}
*/
.face-list{
	display: flex;
	flex-wrap: wrap;
	justify-content:center;
	align-content:flex-start;
	/* height: 320upx; */
/* 	height:calc( 320upx + env(safe-area-inset-bottom) / 1.5 );
	padding-bottom:calc( env(safe-area-inset-bottom) / 1.5 ); */
} 
</style>
